package com.mes.license_demo;

import com.mes.license_demo.license.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

/**
 * @Author: ZZB
 * @Description:
 * @Date: create in 2020/8/20 15:28
 */

@Component
public class MakeLicenseUtils implements CommandLineRunner {

    // 证书subject
    @Value("${license.subject}")
    private String subject;

    // 公钥别称
    @Value("${license.publicAlias}")
    private String publicAlias;

    // 访问公钥库的密码
    @Value("${license.storePass}")
    private String storePass;
    // 访问公钥库的密码
    @Value("${license.keyPass}")
    private String keyPass;

    // 证书生成路径
    @Value("${license.licensePath}")
    private String licensePath;

    // 密钥库存储路径
    @Value("${license.publicKeysStorePath}")
    private String publicKeysStorePath;

    @Value("${license.check}")
    private boolean check;

    // 密钥库存储路径
    @Value("${license.privateKeysPath}")
    private String privateKeysPath;
    // 密钥库存储路径
    @Value("${license.licenseYears}")
    private Integer licenseYears;

    @Override
    public void run(String... args) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LicenseCreatorParam param=new LicenseCreatorParam();
        param.setSubject(subject);
        param.setPrivateAlias("privateKey");
        param.setKeyPass(keyPass);
        param.setStorePass(storePass);
        param.setConsumerType("user");
        param.setConsumerAmount(1);
        param.setPrivateKeysStorePath(privateKeysPath);
        param.setLicensePath(licensePath);
        String curDate = TimeUtil.getCurDate();
        param.setIssuedTime(simpleDateFormat.parse(curDate));
        param.setExpiryTime(simpleDateFormat.parse(TimeUtil.getNextYear(licenseYears)));
//        param.setDescription("这是证书描述信息");
        //
        if(StringUtils.isBlank(param.getLicensePath())){
            param.setLicensePath(licensePath);
        }
        LicenseCheckModel serverInfos = getServerInfos();
        param.setLicenseCheckModel(serverInfos);

        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();
        System.out.println(result);
    }

    private LicenseCheckModel getServerInfos() {
        // 操作系统类型
        String osName = System.getProperty("os.name").toLowerCase();
        AbstractServerInfos abstractServerInfos;
        // 根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        } else {//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }
        return abstractServerInfos.getServerInfos();
    }
}
